package com.richfun.boot.common.util;

import com.richfun.boot.common.exception.SysException;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO 自定义全局返回结果类
 * @author geYang
 * @date 2018-05-11
 */
public final class R extends HashMap<String, Object> implements Serializable{
    private static final long serialVersionUID = 1L;
    
    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    private final static int CODE_SUCCESS = 200;
    private final static int CODE_ERROR = 500;
    
    private R() {}
    
    private R(boolean b) {
        int code = b ? CODE_SUCCESS : CODE_ERROR;
        put("code", code);
        put("success", b);
    }
    
    public static R ok() {
        return new R(true);
    }
    
    public static R ok(Object data) {
        return R.ok().put("data", data);
    }
    
    public static R ok(Map<String, Object> map) {
        R r = R.ok();
        r.putAll(map);
        return r;
    }
    
    public static R err() {
        return new R(false);
    }
    
    public static R err(String msg) {
        return R.err().put("msg", msg);
    }
    
    public static R err(int code, String msg) {
        return R.err(msg).put("code", code);
    }
    
    public static R err(SysException e) {
        return R.err(e.getCode(), e.getMessage());
    }
    
}
